package cn.com.waajyun.shanbayscan.service.impl;

import cn.com.waajyun.shanbayscan.dto.ArticleDto;
import cn.com.waajyun.shanbayscan.service.ArticleService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: Feng
 * @Date: 2018/12/21 14:55
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    private final Log LOG = LogFactory.getLog(ArticleServiceImpl.class);
    private ReentrantLock reentrantLock = new ReentrantLock(true);

    @Override
    public boolean autoPostArticleData() throws IOException {
        return true;
    }

    @Override
    public List<ArticleDto> getPageContent(int page, Integer prePageTotal, boolean following) throws IOException {
        List<ArticleDto> articles;
        try {
            reentrantLock.lock();
            String url = "https://www.shanbay.com/api/v1/team/393008/thread/?page=" + page + "&_=1545464398395";
            JSONObject result = JSONObject.parseObject(getContent(url));
            articles = Lists.newArrayList();
            if ("SUCCESS".equalsIgnoreCase(result.getString("msg"))) {
                int total = result.getJSONObject("data").getIntValue("total");
                if (following && prePageTotal != null && total != prePageTotal) {
                    LOG.debug("重新获取数据，获取页码：" + page);
                    return getPageContent(1, null, true);
                }
                int pageSize = result.getJSONObject("data").getIntValue("ipp");
                int pageTotal = (total + pageSize - 1) / pageSize;
                List<ArticleDto> records = JSONArray.parseArray(result.getJSONObject("data").getString("objects"), ArticleDto.class);
                articles.addAll(records);
                if (following && pageTotal > page) {
                    LOG.info("获取页码：" + page + ", 页数：" + pageTotal);
                    articles.addAll(getPageContent(page + 1, total, true));
                }
            }
        } finally {
            reentrantLock.unlock();
        }
        return articles;
    }

    private String getContent(String url) throws IOException {
        CloseableHttpClient httpCilent = HttpClients.createDefault();//Creates CloseableHttpClient instance with default configuration.
        HttpGet httpGet = new HttpGet(url);
        try {
            CloseableHttpResponse response = httpCilent.execute(httpGet);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String readLine = null;
            StringBuilder builder = new StringBuilder();
            while((readLine = bufferedReader.readLine()) != null) {
                builder.append(readLine);
            }
            return builder.toString();
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                httpCilent.close();
            } catch (IOException e) {
                throw e;
            }
        }
    }

}
